package program.queue;

import program.array.ArrayV2;

/**
 * 循环队列:
 *  1. 弥补数组队列出队的问题.
 *  2. 基础概念:
 *      1. front == tail: 代表队列为空
 *      2. (tail + 1) % c == front: 代表队列已满(c为capacity)
 *      3. capacity中会浪费掉一个空间;
 */
public class LoopQueue<E> implements Queue<E> {

    private E[] data;

    private int front;

    private int tail;

    private int size;

    public LoopQueue(int capacity) {
        // +1: 因为计算队列是否满的时候, 会浪费掉一个空间.
        data = (E[]) new Object[capacity + 1] ;
        tail = 0;
        front = 0;
        size = 0;
    }

    public LoopQueue() {
        this(10);
    }

    @Override
    public int getSize() {
        return size;
    }

    public int getCapacity() {
        // -1: 因为初始化数组的时候, 多占用了一个空间.
        return data.length - 1;
    }

    @Override
    public boolean isEmpty() {
        return front == tail;
    }

    @Override
    public void enqueue(E e) {
        if ((tail + 1) %  data.length == front) {
            // 队列已满, 进行扩容
            resize(getCapacity() * 2);
        }

        data[tail] = e;
        tail = (tail + 1) % data.length;
        size ++;
    }

    @Override
    public E dequeue() {
        if (isEmpty()) {
            throw new IllegalArgumentException("Queue is empty!");
        }

        E ret = data[front];
        data[front] = null;
        front = (front + 1) % data.length;
        size --;
        if (size == getCapacity() / 4 && getCapacity() / 2 != 0) {
            resize(getCapacity() / 2);
        }

        return ret;
    }

    @Override
    public E getFront() {
        if (isEmpty()) {
            throw new IllegalArgumentException("Queue is empty!");
        }

        return data[front];
    }

    @Override
    public String toString() {
        StringBuilder resultStr = new StringBuilder();
        int size = getSize();
        resultStr.append(String.format("Queue size:%d, capacity: %d\n", size, getCapacity()));
        resultStr.append("front [");
        for (int i = front; i != tail; i = (i + 1) % data.length) {
            resultStr.append(data[i]);
            if ((i + 1) % data.length != tail) {
                resultStr.append(", ");
            }
        }

        resultStr.append("]tail");
        return resultStr.toString();
    }

    private void resize(int newCapacity) {
        E[] newData = (E[]) new Object[newCapacity];
        for (int i = 0; i < size; i++) {
            /**
             * (i+front): 因为是循环队列, 可能front已经不是从0开始了; 因此, 需要从front开始;
             * %data.length: 可能tail到front之后, 保证data[index]的index始终在0 - data.length这个范围中.
             */
            newData[i] = data[(i + front) % data.length];
        }

        data = newData;
        front = 0;
        tail = size;
    }
}
